const User = require('../models/users')
const jwt = require('jsonwebtoken')
const { secret } = require('../config')
class UsersCtl {
  async find (ctx) {
    const users = await User.find()
    ctx.body = users
  }
  // 授权
  async checkOwner (ctx, next) {
    // console.log(ctx.params.id, ctx.state.user._id)
    if (ctx.params.id !== ctx.state.user._id) {
      ctx.throw(403, '没有权限')
    }
    await next()
  }
  async findById (ctx) {
    const { id } = ctx.params
    const user = User.findById({ _id: id })
    ctx.body = user
  }
  async create (ctx) {
    ctx.verifyParams({
      username: { type: 'string', required: true },
      password: { type: 'string', required: true }
    })
    const { username } = ctx.request.body
    const repeatedUser = await User.findOne({ username })
    if (repeatedUser) {
      ctx.throw(409, '用户已存在')
    }
    const user = await new User(ctx.request.body).save()
    ctx.body = user
  }
  async update (ctx) {
    ctx.verifyParams({
      username: { type: 'string', required: true },
      password: { type: 'string', required: false }
    })
    const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    if (!user) { ctx.throw(404, '用户不存在') }
    ctx.body = user
  }
  async login (ctx) {
    ctx.verifyParams({
      username: { type: 'string', required: true },
      password: { type: 'string', required: true }
    })
    const user = await User.findOne(ctx.request.body)
    if (!user) { ctx.throw(401, '用户名或密码不正确') }
    const { _id, username } = user
    const token = jwt.sign({ _id, username }, secret, {expiresIn: '1d'})
    ctx.body = { token }
  }
}

module.exports = new UsersCtl()